import classNames from 'classnames';
import React from 'react';

export interface ISwitchProps {
  className?: string; // 样式
  style?: React.CSSProperties; //  样式
  label?: string;
  textAlign?: string;
  defaultChecked?: boolean;
  checked?: boolean;
  disabled?: boolean;
  name?: string;
  checkedChildren?: React.ReactNode;
  unCheckedChildren?: React.ReactNode;
  onChange?: (checked: boolean) => void;
}

export interface ISwitchState {
  checked: boolean;
}

export class Switch extends React.Component<ISwitchProps, ISwitchState> {
  public static defaultProps = {
    textAlign: 'left',
    checkedChildren: '',
    unCheckedChildren: '',
  };

  public static getDerivedStateFromProps(props: ISwitchProps, state: ISwitchState) {
    if ('checked' in props) {
      return {
        checked: props.checked,
      };
    }
    return null;
  }

  constructor(props: ISwitchProps) {
    super(props);

    this.state = {
      checked: props.defaultChecked || props.checked || false,
    };

    this.onChange = this.onChange.bind(this);
  }

  public onChange(e: React.ChangeEvent) {
    if (!('checked' in this.props)) {
      this.setState({
        checked: (e.target as any).checked,
      });
    }
    if (this.props.onChange) {
      this.props.onChange((e.target as any).checked);
    }
  }

  public render() {
    const {
      className,
      style,
      label,
      textAlign,
      name,
      disabled,
      onChange,
      checkedChildren,
      unCheckedChildren,
      checked: checkedProp,
      defaultChecked: defaultCheckedProp,
      ...props } = this.props;

    const { checked } = this.state;

    return (
      <div className={classNames('br-switch', className)} style={style}>
        <label className="br-switch__label">
          {label}
          <div className={classNames('br-switch__container', {
            'pull-left': textAlign === 'right',
            'pull-right': textAlign !== 'right',
          })}>
            <input
              className="br-switch__input"
              type="checkbox"
              name={name || 'switch'}
              checked={checked}
              onChange={this.onChange}
              disabled={disabled}
              {...props}
            />
            <span className={classNames('br-switch__indicator', {
              'br-switch__indicator-disabled': disabled,
            })}></span>
            {
              checkedChildren && unCheckedChildren && <span className={classNames('br-switch__text', {
                'br-switch__text-right': !checked,
                'br-switch__text-left': checked,
                'br-switch__text-disabled': disabled,
              })}>{checked ? checkedChildren : unCheckedChildren}</span>
            }
          </div>
        </label>
      </div>
    );
  }
}
